<template>
  <div class="schedule-plan-page">
    <!-- 搜索表单区域 -->
    <el-form :model="searchForm" inline label-width="80px" class="search-form">
      <el-form-item label="班组类型">
        <el-select v-model="searchForm.teamType" placeholder="请选择班组类型" clearable>
          <el-option v-for="type in teamTypes" :key="type" :label="type" :value="type" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划编号">
        <el-input v-model="searchForm.planId" placeholder="请输入计划编号" clearable />
      </el-form-item>
      <el-form-item label="计划名称">
        <el-input v-model="searchForm.planName" placeholder="请输入计划名称" clearable />
      </el-form-item>
      <el-form-item label="开始日期">
        <el-date-picker v-model="searchForm.startDate" type="date" placeholder="请选择开始日期" clearable />
      </el-form-item>
      <el-form-item label="结束日期">
        <el-date-picker v-model="searchForm.endDate" type="date" placeholder="请选择结束日期" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-btns">
      <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="!hasSelectedRows">删除</el-button>
      <el-button type="success" icon="Edit" @click="handleBatchEdit" :disabled="!isSingleSelected">修改</el-button>
    </div>

    <!-- 数据表格区域 -->
    <el-table 
      :data="page.records" 
      border 
      style="width: 100%" 
      :header-cell-style="{ background: '#f8f9fa' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="planId" label="计划编号" />
      <el-table-column prop="planName" label="计划名称" />
      <el-table-column prop="teamType" label="班组类型" />
      <el-table-column prop="startDate" label="开始日期" />
      <el-table-column prop="endDate" label="结束日期" />
      <el-table-column prop="shiftMode" label="轮班方式" />
      <el-table-column prop="shiftCycle" label="倒班方式" />
      <el-table-column prop="status" label="单据状态" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleRowEdit(scope.row)">修改</el-button>
          <el-button type="text" icon="Delete" text-color="red" @click="handleRowDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination 
      @size-change="handleSearch" 
      @current-change="handleSearch" 
      v-model:current-page="page.current"
      :page-sizes="[10, 20, 30, 40]" 
      v-model:page-size="page.size" 
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total" 
      class="pagination" 
    />

    <!-- 新增/编辑排班计划弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '修改排班计划' : '添加排班计划'" 
      width="60%"
    >
      <el-form 
        :model="dialogForm" 
        ref="dialogFormRef" 
        label-width="120px" 
        :rules="dialogFormRules"
      >
        <el-form-item label="计划编号" prop="planId">
          <el-input 
            v-model="dialogForm.planId" 
            placeholder="请输入计划编号" 
            :disabled="autoGenerate || isEdit"
          />
          <el-switch 
            v-model="autoGenerate" 
            active-text="自动生成" 
            inactive-text="手动输入" 
            @change="handleAutoGenerate"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName" required>
          <el-input v-model="dialogForm.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="班组类型" prop="teamType" required>
          <el-select v-model="dialogForm.teamType" placeholder="请选择班组类型">
            <el-option v-for="type in teamTypes" :key="type" :label="type" :value="type" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate" required>
          <el-date-picker 
            v-model="dialogForm.startDate" 
            type="date" 
            placeholder="请选择开始日期" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate" required>
          <el-date-picker 
            v-model="dialogForm.endDate" 
            type="date" 
            placeholder="请选择结束日期" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="轮班方式" prop="shiftMode" required>
          <el-select v-model="dialogForm.shiftMode" placeholder="请选择轮班方式">
            <el-option label="白班" value="白班" />
            <el-option label="两班倒" value="两班倒" />
            <el-option label="三班倒" value="三班倒" />
          </el-select>
        </el-form-item>
        <el-form-item label="倒班方式" prop="shiftCycle" required>
          <el-select v-model="dialogForm.shiftCycle" placeholder="请选择倒班方式">
            <el-option label="按天" value="按天" />
            <el-option label="按周" value="按周" />
            <el-option label="按月" value="按月" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态" prop="status" required>
          <el-select v-model="dialogForm.status" placeholder="请选择单据状态">
            <el-option label="草稿" value="草稿" />
            <el-option label="已确认" value="已确认" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="dialogForm.remarks" placeholder="请输入备注内容" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog 
      v-model="deleteDialogVisible" 
      title="删除确认" 
      width="400px"
      :before-close="handleDeleteDialogClose"
    >
      <p>{{ deleteDialogContent }}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteConfirm">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from '@/api/request'
import { ref, reactive, computed } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'

// 1. 基础数据定义
// 班组类型选项
const teamTypes = ref(['注塑', '仓库', '组装'])
// 搜索表单数据
const searchForm = ref({
  teamType: '',
  planId: '',
  planName: '',
  startDate: null,
  endDate: null
})
// 在 <script setup> 开头定义工具函数
const formatDate = (date) => {
  if (!date) return null;
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，补0
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 分页数据（与班组页面结构一致）
const page = ref({
  current: 1,
  size: 10,
  total: 0,
  records: []
})
// 表格选中行数据
const selectedRows = ref([])
// 弹窗控制相关
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEdit = ref(false) // 标记弹窗是新增还是编辑状态
const autoGenerate = ref(false) // 控制计划编号是否自动生成
const dialogFormRef = ref(null) // 弹窗表单引用（用于校验）
// 删除相关
const deleteTarget = ref(null)
const deleteDialogContent = ref('') // 删除弹窗提示内容

// 2. 弹窗表单数据与校验规则
const dialogForm = reactive({
  planId: '',
  planName: '',
  teamType: '',
  startDate: null,
  endDate: null,
  shiftMode: '',
  shiftCycle: '',
  status: '草稿', // 默认草稿状态
  remarks: ''
})
// 表单校验规则
const dialogFormRules = ref({
  planId: [
    { required: true, message: '请输入计划编号', trigger: 'blur' },
    { min: 3, max: 20, message: '计划编号长度需在3-20个字符之间', trigger: 'blur' }
  ],
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' },
    { min: 1, max: 50, message: '计划名称长度需在1-50个字符之间', trigger: 'blur' }
  ],
  teamType: [
    { required: true, message: '请选择班组类型', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (dialogForm.startDate && value < dialogForm.startDate) {
          callback(new Error('结束日期不能早于开始日期'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  shiftMode: [
    { required: true, message: '请选择轮班方式', trigger: 'change' }
  ],
  shiftCycle: [
    { required: true, message: '请选择倒班方式', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择单据状态', trigger: 'change' }
  ]
})

// 3. 计算属性（控制按钮禁用状态）
// 是否有选中行（控制批量删除按钮）
const hasSelectedRows = computed(() => {
  return selectedRows.value.length > 0
})
// 是否仅选中一行（控制批量修改按钮）
const isSingleSelected = computed(() => {
  return selectedRows.value.length === 1
})

// 4. 核心功能方法
/**
 * 搜索与分页核心方法
 * 触发时机：页面初始化、点击搜索、切换页码、切换页大小
 */
const handleSearch = () => {
  // 显示加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  // 调用接口：传递搜索条件和分页参数
  request({
    url: '/scheduling-plan/list',
    method: 'get',
    params: {
      // 搜索条件（与表单字段对应）
      teamType: searchForm.value.teamType,
      planId: searchForm.value.planId,
      planName: searchForm.value.planName,
     startDate: searchForm.value.startDate ? formatDate(searchForm.value.startDate) : null,
endDate: searchForm.value.endDate ? formatDate(searchForm.value.endDate) : null,
      // 分页参数（与page对象对应）
      current: page.value.current,
      size: page.value.size
    }
  }).then(res => {
    console.log(res)
    if (res.code==200) {
      page.value = res.data // 直接赋值分页对象（包含当前页数据records）
    } else {
      page.value.records = []
      page.value.total = 0
      ElMessage.warning('未查询到符合条件的排班计划')
    }
  }).catch(error => {
    console.error('排班计划查询失败：', error)
    ElMessage.error('搜索失败，请重试')
    page.value.records = []
    page.value.total = 0
  }).finally(() => {
    // 关闭加载状态
    loading.close()
  })
}

// 页面初始化时执行搜索
handleSearch();

/**
 * 重置搜索表单
 */
const handleReset = () => {
  // 清空搜索表单
  searchForm.value = {
    teamType: '',
    planId: '',
    planName: '',
    startDate: null,
    endDate: null
  }
  // 重置分页到第一页并重新搜索
  page.value.current = 1
  handleSearch();
}

/**
 * 表格选中行变化事件
 * @param {Array} val - 选中的行数据数组
 */
const handleSelectionChange = (val) => {
  selectedRows.value = val // 同步选中行数据
}

/**
 * 新增排班计划
 */
const handleAdd = () => {
  // 重置弹窗状态
  isEdit.value = false
  autoGenerate.value = false
  dialogVisible.value = true
  // 重置弹窗表单（清空数据+清除校验状态）
  if (dialogFormRef.value) {
    dialogFormRef.value.resetFields()
  }
  // 重置表单默认值
  dialogForm.status = '草稿'
  dialogForm.planId = ''
}

/**
 * 自动生成计划编号
 * @param {Boolean} val - 自动生成开关状态
 */
const handleAutoGenerate = (val) => {
  if (val) {
    // 规则：PLAN + 年月日（YYYYMMDD） + 6位随机数
    const date = new Date()
    const dateStr = date.getFullYear() + 
                    String(date.getMonth() + 1).padStart(2, '0') + 
                    String(date.getDate()).padStart(2, '0')
    const randomStr = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
    dialogForm.planId = `PLAN${dateStr}${randomStr}`
  } else {
    dialogForm.planId = ''
  }
}

/**
 * 弹窗确定按钮（新增/编辑提交）
 */
const handleDialogConfirm = () => {
  // 表单校验
  dialogFormRef.value.validate((valid) => {
    if (!valid) return

    // 处理日期格式（转为后端需要的字符串格式）
    const submitForm = {
      ...dialogForm,
     startDate: dialogForm.startDate ? formatDate(dialogForm.startDate) : null,
endDate: dialogForm.endDate ? formatDate(dialogForm.endDate) : null,
    }

    // 构建请求配置（新增用post，编辑用put）
    const requestConfig = {
      url: isEdit.value ? '/scheduling-plan/update' : '/scheduling-plan/add',
      method: isEdit.value ? 'put' : 'post',
      data: submitForm
    }

    // 提交请求
    request(requestConfig).then(res => {
      dialogVisible.value = false // 关闭弹窗
      if (res.code==200) {
        ElMessage.success(isEdit.value ? '排班计划修改成功' : '排班计划新增成功')
        handleSearch() // 重新加载数据
       
      } else {
        ElMessage.error(res.message || (isEdit.value ? '修改失败' : '新增失败'))
         handleSearch() // 重新加载表格数据
      }
    }).catch(error => {
      console.error('提交失败：', error)
      ElMessage.error('网络错误，操作失败')
    })
  })
}

/**
 * 批量修改（从选中行获取数据）
 */
const handleBatchEdit = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条数据进行修改')
    return
  }
  
  const row = selectedRows.value[0]
  handleRowEdit(row)
}

/**
 * 行内修改
 * @param {Object} row - 当前行数据
 */
const handleRowEdit = (row) => {
  // 重置弹窗状态
  isEdit.value = true
  dialogVisible.value = true
  autoGenerate.value = false
  
  // 回显数据到表单
  dialogForm.planId = row.planId || ''
  dialogForm.planName = row.planName || ''
  dialogForm.teamType = row.teamType || ''
  dialogForm.startDate = row.startDate ? new Date(row.startDate) : null
  dialogForm.endDate = row.endDate ? new Date(row.endDate) : null
  dialogForm.shiftMode = row.shiftMode || ''
  dialogForm.shiftCycle = row.shiftCycle || ''
  dialogForm.status = row.status || '草稿'
  dialogForm.remarks = row.remarks || ''
}

/**
 * 批量删除
 */
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择需要删除的数据')
    return
  }
  
  deleteTarget.value = selectedRows.value
  deleteDialogContent.value = `确定要删除选中的 ${selectedRows.value.length} 条排班计划吗？`
  deleteDialogVisible.value = true
}

/**
 * 行内删除
 * @param {Object} row - 当前行数据
 */
const handleRowDelete = (row) => {
  deleteTarget.value = [row]
  deleteDialogContent.value = `确定要删除排班计划【${row.planName}】吗？`
  deleteDialogVisible.value = true
}

/**
 * 关闭删除弹窗时重置状态
 */
const handleDeleteDialogClose = () => {
  deleteTarget.value = null
  deleteDialogContent.value = ''
  deleteDialogVisible.value = false
}

/**
 * 确认删除
 */
const handleDeleteConfirm = () => {
  if (!deleteTarget.value || deleteTarget.value.length === 0) {
    handleDeleteDialogClose()
    return
  }
  
  // 获取所有要删除的计划编号
  const planIds = deleteTarget.value.map(item => item.planId)
  
  request({
    url: '/scheduling-plan/delete',
    method: 'delete',
    data:  planIds,
  }).then(res => {
    if (res.code==200) {
      ElMessage.success('删除成功')
      handleSearch() // 重新加载数据
    } else {
      ElMessage.error(res.message || '删除失败')
      handleSearch() // 重新加载数据
    }
  }).catch(error => {
    console.error('删除失败：', error)
    ElMessage.error('网络错误，删除失败')
  }).finally(() => {
    handleDeleteDialogClose()
  })
}
</script>

<style scoped>
.schedule-plan-page {
  padding: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.operation-btns {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

:deep(.el-select) {
  width: 200px !important;
}

:deep(.el-select-dropdown) {
  width: 200px !important;
  min-width: auto !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
